<template>
  <div class="profile-container">
    <div class="profile-header">
      <a-button @click="$router.go(-1)" type="text" shape="circle">
        <ArrowLeftOutlined />
      </a-button>
      <h1>个人资料</h1>
    </div>

    <div class="profile-content">
      <div class="profile-card">
        <div class="avatar-section">
          <a-upload
            :show-upload-list="false"
            :before-upload="beforeUpload"
            :custom-request="customUpload"
            accept="image/*"
          >
            <div class="avatar-container">
              <a-avatar :size="120" :src="authStore.user?.avatar">
                {{ authStore.user?.displayName?.[0] || authStore.user?.username?.[0] }}
              </a-avatar>
              <div class="avatar-overlay">
                <CameraOutlined />
                <span>更换头像</span>
              </div>
            </div>
          </a-upload>
          <div class="avatar-loading" v-if="isUploadingAvatar">
            <a-spin size="small" />
            <span>上传中...</span>
          </div>
          <p class="avatar-hint">点击头像更换图片</p>
        </div>

        <a-form
          :model="form"
          :rules="rules"
          @finish="handleUpdateProfile"
          layout="vertical"
          class="profile-form"
        >
          <a-form-item label="用户名" name="username">
            <a-input v-model:value="form.username" disabled />
          </a-form-item>

          <a-form-item label="邮箱" name="email">
            <a-input v-model:value="form.email" disabled />
          </a-form-item>

          <a-form-item label="显示名称" name="displayName">
            <a-input
              v-model:value="form.displayName"
              placeholder="请输入显示名称"
            />
          </a-form-item>

          <a-form-item label="个人简介" name="bio">
            <a-textarea
              v-model:value="form.bio"
              placeholder="介绍一下自己..."
              :rows="4"
            />
          </a-form-item>

          <a-form-item>
            <a-space>
              <a-button
                type="primary"
                html-type="submit"
                :loading="isUpdating"
              >
                保存更改
              </a-button>
              <a-button @click="resetForm">
                重置
              </a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </div>

      <div class="security-card">
        <h3>安全设置</h3>
        <a-form
          :model="passwordForm"
          :rules="passwordRules"
          @finish="handleChangePassword"
          layout="vertical"
        >
          <a-form-item label="当前密码" name="currentPassword">
            <a-input-password
              v-model:value="passwordForm.currentPassword"
              placeholder="请输入当前密码"
            />
          </a-form-item>

          <a-form-item label="新密码" name="newPassword">
            <a-input-password
              v-model:value="passwordForm.newPassword"
              placeholder="请输入新密码"
            />
          </a-form-item>

          <a-form-item label="确认新密码" name="confirmPassword">
            <a-input-password
              v-model:value="passwordForm.confirmPassword"
              placeholder="请再次输入新密码"
            />
          </a-form-item>

          <a-form-item>
            <a-button
              type="primary"
              html-type="submit"
              :loading="isChangingPassword"
            >
              修改密码
            </a-button>
          </a-form-item>
        </a-form>
      </div>

      <div class="danger-zone">
        <h3>危险操作</h3>
        <a-button type="primary" danger @click="handleLogout">
          <LogoutOutlined />
          退出登录
        </a-button>
      </div>
    </div>

    <a-alert
      v-if="authStore.error"
      :message="authStore.error"
      type="error"
      show-icon
      closable
      @close="authStore.clearError"
      class="error-alert"
    />
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import {
  ArrowLeftOutlined,
  CameraOutlined,
  LogoutOutlined
} from '@ant-design/icons-vue'
import { useAuthStore } from '@/stores/auth'
import { apiService } from '@/services/api'
import type { UploadResult } from '@/types'

const router = useRouter()
const authStore = useAuthStore()

const isUpdating = ref(false)
const isChangingPassword = ref(false)
const isUploadingAvatar = ref(false)

const form = reactive({
  username: '',
  email: '',
  displayName: '',
  bio: ''
})

const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const rules = {
  displayName: [
    { max: 100, message: '显示名称长度不能超过100个字符' }
  ],
  bio: [
    { max: 500, message: '个人简介长度不能超过500个字符' }
  ]
}

const validateConfirmPassword = (_rule: any, value: string) => {
  if (value && value !== passwordForm.newPassword) {
    return Promise.reject('两次输入的密码不一致')
  }
  return Promise.resolve()
}

const passwordRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码' },
    { min: 6, max: 100, message: '密码长度在6-100个字符之间' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码' },
    { validator: validateConfirmPassword }
  ]
}

onMounted(() => {
  if (authStore.user) {
    form.username = authStore.user.username
    form.email = authStore.user.email
    form.displayName = authStore.user.displayName || ''
    form.bio = '' // 如果有 bio 字段的话
  }
})

const resetForm = () => {
  if (authStore.user) {
    form.username = authStore.user.username
    form.email = authStore.user.email
    form.displayName = authStore.user.displayName || ''
    form.bio = ''
  }
}

const handleUpdateProfile = async () => {
  isUpdating.value = true
  try {
    // 只更新显示名称，保留现有头像
    await authStore.updateUser({
      displayName: form.displayName,
      avatar: authStore.user?.avatar // 保留现有头像
    })
    message.success('个人资料更新成功')
  } catch (error) {
    // 错误已在 store 中处理
  } finally {
    isUpdating.value = false
  }
}

const handleChangePassword = async () => {
  isChangingPassword.value = true
  try {
    await authStore.changePassword(
      passwordForm.currentPassword,
      passwordForm.newPassword
    )
    message.success('密码修改成功')
    
    // 清空表单
    passwordForm.currentPassword = ''
    passwordForm.newPassword = ''
    passwordForm.confirmPassword = ''
  } catch (error) {
    // 错误已在 store 中处理
  } finally {
    isChangingPassword.value = false
  }
}

// 上传前验证
const beforeUpload = (file: File) => {
  console.log('beforeUpload called with file:', file)

  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    message.error('请选择图片文件')
    return false
  }

  // 验证文件大小 (5MB)
  if (file.size > 5 * 1024 * 1024) {
    message.error('图片大小不能超过 5MB')
    return false
  }

  return true
}

// 自定义上传
const customUpload = async (options: any) => {
  console.log('customUpload called with options:', options)
  const { file } = options

  try {
    isUploadingAvatar.value = true
    const result: UploadResult = await apiService.uploadAvatar(file)

    // 更新头像URL - 静态文件不需要/api前缀
    const baseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:5276/api'
    const staticBaseUrl = baseUrl.replace('/api', '')
    const fullAvatarUrl = `${staticBaseUrl}${result.url}`

    // 更新用户信息
    await authStore.updateUser({ avatar: fullAvatarUrl })

    message.success('头像上传成功')
    options.onSuccess(result)
  } catch (error: any) {
    console.error('Upload error:', error)
    message.error(error.response?.data?.message || '头像上传失败')
    options.onError(error)
  } finally {
    isUploadingAvatar.value = false
  }
}

const handleLogout = async () => {
  try {
    await authStore.logout()
    message.success('已退出登录')
    router.push('/login')
  } catch (error) {
    message.error('退出登录失败')
  }
}
</script>

<style scoped>
.profile-container {
  height: 100vh;
  width: 100vw;
  background: #f5f5f5;
  padding: 20px;
  margin: 0;
  overflow-y: auto;
  position: fixed;
  top: 0;
  left: 0;
}

.profile-header {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 24px;
}

.profile-header h1 {
  margin: 0;
  color: #1f2937;
  font-size: 24px;
  font-weight: 600;
}

.profile-content {
  max-width: 800px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.profile-card,
.security-card,
.danger-zone {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  margin-bottom: 32px;
}

.avatar-container {
  position: relative;
  cursor: pointer;
  border-radius: 50%;
  overflow: hidden;
  transition: all 0.3s ease;
}

.avatar-container:hover {
  transform: scale(1.05);
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  opacity: 0;
  transition: opacity 0.3s ease;
  border-radius: 50%;
}

.avatar-container:hover .avatar-overlay {
  opacity: 1;
}

.avatar-overlay span {
  font-size: 12px;
  margin-top: 4px;
}

.avatar-loading {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
  font-size: 14px;
}

.avatar-hint {
  color: #666;
  font-size: 12px;
  margin: 0;
  text-align: center;
}

.change-avatar-btn {
  border-radius: 20px;
}

.profile-form {
  max-width: 500px;
  margin: 0 auto;
}

.security-card h3,
.danger-zone h3 {
  margin: 0 0 24px 0;
  color: #1f2937;
  font-size: 18px;
  font-weight: 600;
}

.danger-zone {
  border: 1px solid #fecaca;
  background: #fef2f2;
}

.error-alert {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 1000;
}

@media (max-width: 768px) {
  .profile-container {
    padding: 16px;
  }
  
  .profile-card,
  .security-card,
  .danger-zone {
    padding: 16px;
  }
}
</style>
